package com.hmy.security.security.service;

import com.hmy.security.entity.Roles;
import com.hmy.security.security.bean.JwtUser;
import com.hmy.security.service.IRolesUserService;
import com.hmy.security.vo.UserRolesVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service("userDetailService")

public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private IRolesUserService rolesUserService;
//    @Autowired
//    private PasswordEncoder passwordEncoder;


    /**
     * 通过用户名去查找数据库中的用户
     * <p>
     *     不存在 - 抛异常{@link UsernameNotFoundException}
     * </p>
     * <p>
     *     存在 - 获取用户的相关信息封装至{@link UserDetails}的实现类中 后续会通过{@link org.springframework.security.authentication.dao.DaoAuthenticationProvider}
     *     调用{@link org.springframework.security.crypto.password.PasswordEncoder}去比对密码是否正确
     * </p>
     *
     * @param s 登陆时输入的用户名
     * @return  用户信息 {@link com.hmy.security.security.bean.JwtUser}
     * @throws UsernameNotFoundException 用户名不存在
     */
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        UserRolesVo userRolesVo = rolesUserService.getRolesByUsername(s);
        JwtUser jwtUser = new JwtUser();
//        jwtUser.setPassword(passwordEncoder.);
        BeanUtils.copyProperties(userRolesVo, jwtUser);
        List<String> roleNames = jwtUser.getRoles().stream().map(Roles::getRoleName).collect(Collectors.toList());
        List<SimpleGrantedAuthority> roles = roleNames.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        jwtUser.setAuthorities(roles);
        return jwtUser;
    }
}
